package dyyx.simplerpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcClientDynamicProxy<T> implements InvocationHandler {
    private Class<T> interfaceClazz;
 
    private final String host;
 
    private final int port;
    
    private final NettyClient nettyClient;

    
 
    public RpcClientDynamicProxy(Class<T> interfaceClazz, String host, int port) throws Exception{
        this.interfaceClazz = interfaceClazz;
        this.host = host;
        this.port = port;
        
        NettyClient nettyClient = new NettyClient(host, port);
        nettyClient.connect();
        this.nettyClient = nettyClient;
        
        
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest request = new RpcRequest();
        String requestId = UUID.randomUUID().toString();
 
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
 
        Class<?>[] parameterTypes = method.getParameterTypes();
 
        request.setRequestId(requestId);
        request.setClassName(className);
        request.setMethodName(methodName);
        request.setParameterTypes(parameterTypes);
        request.setParameters(args);
 
        // NettyClient nettyClient = new NettyClient(host, port);
        // nettyClient.connect();
        RpcResponse send = nettyClient.send(request);
        return send.getResult();
    }
 
    @SuppressWarnings("unchecked")
    public T getProxy() {
        return (T) Proxy.newProxyInstance(
                interfaceClazz.getClassLoader(),
                new Class<?>[]{interfaceClazz},
                this
 
        );
    }
}

